package 每日一题;

import java.util.ArrayList;
import java.util.List;

/**
 * 515. 在每个树行中找最大值
 * 给定一棵二叉树的根节点 root ，请找出该二叉树中每一层的最大值。
 *
 *
 *
 * 示例1：
 *
 *
 *
 * 输入: root = [1,3,2,5,3,null,9]
 * 输出: [1,3,9]
 * 示例2：
 *
 * 输入: root = [1,2,3]
 * 输出: [1,3]
 *
 *
 * 提示：
 *
 * 二叉树的节点个数的范围是 [0,104]
 * -231 <= Node.val <= 231 - 1
 *
 */
public class D20220624_T0515 {

    ArrayList<Integer> result = new ArrayList<>();

    //层序遍历
    public List<Integer> largestValues(TreeNode root) {
        ArrayList<TreeNode> curr = new ArrayList<>();
        curr.add(root);

        if (root == null) return result;
        while (!curr.isEmpty()) {
            curr = findNextNodes(curr);
        }
        return result;
    }

    //返回下一层的节点 并将本层最大值放入结果列表中
    public ArrayList<TreeNode> findNextNodes(ArrayList<TreeNode> list) {
        int max = Integer.MIN_VALUE;
        ArrayList<TreeNode> nextNodes = new ArrayList<>();
        for (TreeNode treeNode : list) {
            if (treeNode.val > max) max = treeNode.val;
            if (treeNode.left != null) nextNodes.add(treeNode.left);
            if (treeNode.right != null) nextNodes.add(treeNode.right);
        }

        result.add(max);
        return nextNodes;
    }

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

}
